using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
  
namespace Coriander.Text.RegularExpressions
{
    /// <summary>
    /// Matches elements in text
    /// </summary>
    /// <remarks>
    /// TODO: Add some value. For example return matches assigned 
    /// to a token so we can do one execute and query results by token.
    /// </remarks>
    public class TokenMatcher
    {
        # region * Fields, properties and ctors *

        PatternTokenList tokens;

        /// <summary>
        /// Gets the set of tokens for the current instance
        /// </summary>
        public PatternTokenList Tokens
        {
            get { return tokens ?? (tokens = new PatternTokenList()); }
        }

        # endregion

        /// <summary>
        /// Gets the set of matches for <paramref name="url">url</paramref>.
        /// </summary>
        /// <returns></returns>
        public Match[] GetMatches(String input)
        {
            if (null == input || Tokens.Count == 0)
                return new Match[0];

            Queue<Match> results = new Queue<Match>();

            MatchCollection matches = null; 

            foreach (PatternToken token in Tokens)
            {
                if (token.RegularExpression != null)
                {
                    if ((matches = token.RegularExpression.Matches(input)).Count > 0)
                    {
                        foreach (Match match in matches)
                        {
                            results.Enqueue(match); 
                        }
                    }
                }
            }

            return results.ToArray();
        }
    }
}